package com.hgnu.dorm.handler;

import cn.dev33.satoken.exception.*;
import cn.dev33.satoken.util.SaResult;
import com.hgnu.dorm.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public SaResult exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return SaResult.error(ex.getMessage());
    }
    /**
     * 捕获权限异常
     */
    @ExceptionHandler
    public SaResult exceptionHandler(NotPermissionException ex){
        log.error("异常信息：{}", ex.getMessage());
        return SaResult.error("无此权限");
    }
    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public SaResult exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + "已存在";
            return SaResult.error(msg);
        }else {
            return SaResult.error("未知异常");
        }
    }

    // 拦截：未登录异常
	@ExceptionHandler(NotLoginException.class)
	public SaResult handlerException(NotLoginException e) {
		// 返回给前端
		return SaResult.error(e.getMessage());
	}


	// 拦截：缺少角色异常
	@ExceptionHandler(NotRoleException.class)
	public SaResult handlerException(NotRoleException e) {
		return SaResult.error("缺少角色：" + e.getRole());
	}

	// 拦截：二级认证校验失败异常
	@ExceptionHandler(NotSafeException.class)
	public SaResult handlerException(NotSafeException e) {
		return SaResult.error("二级认证校验失败：" + e.getService());
	}

	// 拦截：服务封禁异常
	@ExceptionHandler(DisableServiceException.class)
	public SaResult handlerException(DisableServiceException e) {
		return SaResult.error("当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
	}

	// 拦截：Http Basic 校验失败异常
	@ExceptionHandler(NotHttpBasicAuthException.class)
	public SaResult handlerException(NotHttpBasicAuthException e) {
		return SaResult.error(e.getMessage());
	}

	// 拦截：其它所有异常
	@ExceptionHandler(Exception.class)
	public SaResult handlerException(Exception e) {
		return SaResult.error(e.getMessage());
	}
}
